import logging
import sys
import os

def setup_logger():
    """
    配置并返回一个logger实例
    """
    # 创建logger
    logger = logging.getLogger('my_app')
    logger.setLevel(logging.DEBUG)

    # 防止重复添加handler
    if logger.handlers:
        return logger

    # 修改这里：使用项目相对路径而不是绝对路径 /app
    # 获取项目根目录
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    log_dir = os.path.join(base_dir, 'logs')
    log_file = os.path.join(log_dir, 'app.log')

    # 确保日志目录存在
    try:
        os.makedirs(log_dir, exist_ok=True)
    except OSError as e:
        # 如果创建目录失败，使用临时目录作为备选方案
        import tempfile
        log_dir = tempfile.gettempdir()
        log_file = os.path.join(log_dir, 'api_test.log')
        print(f"Warning: Using temp directory for logs: {log_file}")

    # 创建文件handler
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setLevel(logging.DEBUG)

    # 创建控制台handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)

    # 创建formatter
    file_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(funcName)s - %(message)s'
    )
    console_formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    # 将formatter添加到handler
    file_handler.setFormatter(file_formatter)
    console_handler.setFormatter(console_formatter)

    # 将handler添加到logger
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    logger.info(f"Logger initialized. Log file: {log_file}")

    return logger

# 创建全局logger实例
logger = setup_logger()